package stock;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.hibernate.Session;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import stock.model.LTModel;
import stock.model.Model2jin3;
import stock.model.SBStock;
import stock.model.SBStock135;
import stock.model.Stocksb;
import stock.testSB.SB;
import stock.testSB.SB1;
import stock.testSB.SBService;
import stock.testSB.Stock1;
import stock.testSB.StockDataUpdater;
import stock.testSB.StockDataUpdater2;
import stock.testSB.TimeZDF;

@Component
public class StockQS implements StockQSInterface {

	public JSONArray getQS() {

		List<String> dateList = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar calendar = Calendar.getInstance();
		// 获取当前日期
		Date now = new Date();
		calendar.setTime(now);
		for (int i = 0; i < 30; i++) {
			calendar.add(Calendar.DATE, -1);
			Date d = calendar.getTime();
			String dateStr = sdf.format(d);
			dateList.add(0, dateStr);
		}
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql = "select t.zt_note from stockqq t where t.date = ?0 and t.zt_note <> '' ";
		List<String> list1 = new ArrayList<String>();
		for (int k = 0; k < dateList.size(); k++) {
			List<String> list = session1.createSQLQuery(sql).setParameter(0, dateList.get(k)).list();
			for (int i = 0; i < list.size(); i++) {
				String[] str = list.get(i).replace("+", "-").split("-");
				for (int j = 0; j < str.length; j++) {
					list1.add(str[j].trim());
				}
			}
		}

		Map<String, Long> countMap = list1.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting()));

		// 将Map按照值（数量）进行降序排序
		Map<String, Long> sortedCountMap = countMap.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

		// 输出每个元素及其数量
		JSONArray array = new JSONArray();
		for (String key : sortedCountMap.keySet()) {
			System.out.println("Key: " + key + ", Value: " + sortedCountMap.get(key));
			JSONObject json = new JSONObject();
			json.put("name", key);
			json.put("value", sortedCountMap.get(key));
			array.add(json);

		}

		return array;

	}

	@Override
	public JSONArray getztConentCode(JSONObject json) {
		// TODO Auto-generated method stub
		String g1 = null, g2 = null, g3 = null, g4 = null;

		if (json.has("g0")) {
			g1 = json.getString("g0");
		}
		if (json.has("g1")) {
			g2 = json.getString("g1");
		}
		if (json.has("g2")) {
			g3 = json.getString("g2");
		}
		if (json.has("g3")) {
			g4 = json.getString("g3");

		}

		String sql = "";
		if (g1 != null && g2 != null && g3 != null && g4 != null) {
			sql = "select * from stockqq t where t.zt_note like '%" + g1 + "%' and t.zt_note like '%" + g2 + "%' and t.zt_note like '%" + g3 + "%' and t.zt_note like '%" + g4 + "%' order by t.code  desc";
		} else if (g1 != null && g2 != null && g3 != null) {
			sql = "select * from stockqq t where t.zt_note like '%" + g1 + "%' and t.zt_note like '%" + g2 + "%' and t.zt_note like '%" + g3 + "%' order by t.code  desc";
		} else if (g1 != null && g2 != null) {
			sql = "select * from stockqq t where t.zt_note like '%" + g1 + "%' and t.zt_note like '%" + g2 + "%' order by t.code  desc";
		} else if (g1 != null) {
			sql = "select * from stockqq t where t.zt_note like '%" + g1 + "%' order by t.code  desc";
		}

		Session session1 = ContextUtil.getSessionFactory1().openSession();

		List<Object[]> list = session1.createSQLQuery(sql).list();

		JSONArray arr = new JSONArray();

		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object[] objects = (Object[]) iterator.next();

			JSONObject json1 = new JSONObject();

			json1.put("code", objects[2]);
			json1.put("date", objects[3]);
			json1.put("name", objects[6]);
			json1.put("shizhi", objects[7]);
			json1.put("ztContent", objects[12]);
			arr.add(json1);
		}
		Map<String, JSONObject> mergedMap = new HashMap<>();
		Map<String, Integer> countMap = new HashMap<>();

		for (int i = 0; i < arr.size(); i++) {
			JSONObject jsonObject = arr.getJSONObject(i);
			String name = jsonObject.getString("name").trim().replace(" ", "");
			if (mergedMap.containsKey(name)) {
				JSONObject existingObject = mergedMap.get(name);
				Iterator<String> keys = jsonObject.keys();
				while (keys.hasNext()) {
					String key = keys.next();
					if (!existingObject.has(key)) {
						existingObject.put(key, jsonObject.get(key));
					}
				}
				countMap.put(name, countMap.get(name) + 1);
			} else {
				mergedMap.put(name, jsonObject);
				countMap.put(name, 1);
			}
		}

		JSONArray mergedArray = new JSONArray();
		for (Map.Entry<String, JSONObject> entry : mergedMap.entrySet()) {
			JSONObject finalObject = entry.getValue();
			finalObject.put("count", countMap.get(entry.getKey()));
			mergedArray.add(finalObject);
		}
		return mergedArray;
	}

	@Override
	public JSONArray getmodel2jin3(JSONArray json) {

		String sql = " select t4.*,t5.pl_content,t5.pldate from (select t1.code,t1.name,t1.gn,t1.shizhi,t1.zt_content,t3.group1 from stock_cls t1 right JOIN (SELECT code1,MAX(group1) AS group1 " + " FROM ltmodel " + " GROUP BY code1 ORDER BY group1 desc) t3 on t1.code = t3.code1  order by t3.group1 desc ) t4 left join model2jin3 t5 on t4.code = t5.code  order by t4.group1 desc  ";
		// TODO Auto-generated method stub
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<Object[]> list = session1.createSQLQuery(sql).list();
		JSONArray arr = new JSONArray();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object[] objects = (Object[]) iterator.next();
			JSONObject json1 = new JSONObject();
			json1.put("code", objects[0]);
			json1.put("name", objects[1]);
			json1.put("gn", objects[2]);
			json1.put("shizhi", objects[3]);
			json1.put("ztContent", objects[4]);
			json1.put("date", objects[5]);
			json1.put("pl_content", objects[6] + "");
			json1.put("pldate", objects[7] + "");
			arr.add(json1);
		}

		session1.close();

		return arr;
	}

	@Override
	public JSONArray addModelContent2jin3(JSONArray jsonarr) {
		// TODO Auto-generated method stub
		List<Model2jin3> list = JSONArray.toList(jsonarr, Model2jin3.class);
		String sql0 = "delete from model2jin3 where 1=1";

		Session session1 = ContextUtil.getSessionFactory1().openSession();

		session1.getTransaction().begin();

		session1.createSQLQuery(sql0).executeUpdate();

		for (int i = 0; i < list.size(); i++) {

			if (null == list.get(i).getPl_content() || list.get(i).getPl_content().length() == 0 || "null".equals(list.get(i).getPl_content())) {
				continue;
			}
			if (null == list.get(i).getPldate() || list.get(i).getPldate().length() == 0) {
				list.get(i).setPldate(DateTools.getCurrentDate("yyyyMMdd"));
			} else {
				list.get(i).setPldate(DateTools.getCurrentDate("yyyyMMdd"));
			}
			session1.save(list.get(i));

		}

		session1.getTransaction().commit();
		session1.clear();
		session1.close();
		return null;
	}

	@Override
	public List<String> get1jin2(JSONObject json) {

		String sql0 = "select DISTINCT(code),diqv from stock_cls t where t.shizhi >50  and t.shizhi <=250";
		Session session1 = ContextUtil.getSessionFactory1().openSession();

		List<Object[]> list = session1.createSQLQuery(sql0).list();

		List<String> list1 = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = list.get(i);
			if ("0".equals(obj[1])) {
				list1.add("sh" + obj[0]);
			} else {
				list1.add("sz" + obj[0]);
			}

		}
		// TODO Auto-generated method stub
		return list1;
	}

	@Override
	public List<StockCls> get1jin2Cls(List<String> list2) {
		// TODO Auto-generated method stub
		String sql = " from StockCls t where t.code in ?0";
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<StockCls> list = session1.createQuery(sql).setParameterList(0, list2).list();
		String sql1 = "SELECT  IF(EXISTS (SELECT * FROM stockqq WHERE zhangdiefu >= 9  and code = ?0 ORDER BY date  DESC LIMIT 10), 1,0) AS result FROM dual";

		List<StockCls> a = new ArrayList<StockCls>();
		for (int i = list.size() - 1; i >= 0; i--) {
			System.out.println(list.get(i).getCode());
			String temp = session1.createSQLQuery(sql1).setParameter(0, list.get(i).getCode()).uniqueResult().toString();
			if ("1".equals(temp)) {
				list.remove(i);
			}
		}
		return list;
	}

	@Override
	public List<String> getZuiJinfanla(String date) {
		// TODO Auto-generated method stub
		String sql = "select DISTINCT(t.code1),t1.diqv from ltmodel t left join stock_cls t1 on t1.code = t.code1  where t.group1  >= ?0  ";
		Calendar calendar = Calendar.getInstance();
		Date now = calendar.getTime();

		// 将日期向前推7天
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		Date sevenDaysAgo = calendar.getTime();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String nowStr = sdf.format(now);
		String sevenDaysAgoStr = sdf.format(sevenDaysAgo);
		System.out.println("当前日期: " + nowStr);
		System.out.println("7天前的日期: " + sevenDaysAgoStr);
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<Object[]> list = session1.createSQLQuery(sql).setParameter(0, Integer.parseInt(sevenDaysAgoStr)).list();

		List<String> list1 = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = list.get(i);
			if ("0".equals(obj[1])) {
				list1.add("sh" + obj[0]);
			} else {
				list1.add("sz" + obj[0]);
			}

		}
		// TODO Auto-generated method stub
		return list1;
	}

	@Override
	public List<StockCls> getZhuijinlaCls(JSONArray jsonall, String tt) {

		List<String> list2 = new ArrayList<String>();

		for (int i = 0; i < jsonall.size(); i++) {
			list2.add(jsonall.getJSONObject(i).getString("code").replace("sz", "").replace("sh", ""));
		}

		Session session1 = ContextUtil.getSessionFactory1().openSession();
//		String sql = "SELECT MAX(dqj) AS max_value FROM ( SELECT dqj FROM stockqq WHERE CODE = ?0 ORDER BY date DESC LIMIT 10 ) subquery";
//		for (int i = 0; i < jsonall.size(); i++) {
//			String code = jsonall.getJSONObject(i).getString("code").replace("sz", "").replace("sh", "");
//			String dqj = jsonall.getJSONObject(i).getString("jiage");
//			String temp = session1.createSQLQuery(sql).setParameter(0, code).uniqueResult().toString();
//			if (Float.parseFloat(dqj) < Float.parseFloat(temp)) {
//
//			} else {
//				System.out.println("dqj" + dqj + ":  历史：" + temp + "未下跌" + (1 - Float.parseFloat(tt)));
//			}
//			list2.add(code);
//		}
//		if (list2.size() == 0) {
//			return null;
//		}
		// TODO Auto-generated method stub
		String sql31 = " from StockCls t where t.code in ?0";
		List<StockCls> list = session1.createQuery(sql31).setParameterList(0, list2).list();

		return list;
	}

	@Transactional
	@Scheduled(cron = "0 0 19 * * ?")
	@Override
	public void getLongHuiTou() {

		String sql = " select DISTINCT(code1) from ltmodel ";
		List<String> list0 = new ArrayList<String>();
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		list0 = session1.createSQLQuery(sql).list();
		LocalDate today = LocalDate.now();
		LocalDate fifteenDaysAgo = today.minusDays(45);
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		System.out.println("当前日期: " + today.format(formatter));
		System.out.println("15天前的日期: " + fifteenDaysAgo.format(formatter));
		DecimalFormat df = new DecimalFormat("0.00");
		if (list0 != null) {
			String sql1 = "select max(dqj)  from stockqq t where t.date > ?0  and t.code =?1";
			String sql1_1 = "select dqj from stockqq t where t.date > ?0  and t.code =?1  order by date desc limit 1 ";
			// String sql2 = " select t.name,t.gn,t.shizhi,t.zt_content,t1.group1 from stock_cls t left join ltmodel t1 on t.code = t1.code1 where t.code =?0 ";
			String sql3 = "update ltmodel  set date= ?0, diefu = ?1  where code1 = ?2 ";
			session1.getTransaction().begin();
			for (int i = 0; i < list0.size(); i++) {
				String code = list0.get(i);
				System.out.println(code);
				String max = session1.createSQLQuery(sql1).setParameter(0, fifteenDaysAgo.format(formatter)).setParameter(1, code).uniqueResult().toString();
				String dqj = session1.createSQLQuery(sql1_1).setParameter(0, fifteenDaysAgo.format(formatter)).setParameter(1, code).uniqueResult().toString();
				Float diefu = (Float.parseFloat(max) - Float.parseFloat(dqj)) / Float.parseFloat(max);
				String diefu1 = df.format(diefu);
				// System.out.println(diefu1);
				// List<Object[]> list2 = session1.createSQLQuery(sql1).setParameter(0, code).list();
				// String count = list2.size() + "";
				// String name = list2.get(0)[0] + "";
				// String gn = list2.get(0)[1] + "";
				// String shizhi = list2.get(0)[2] + "";
				// String ztContent = list2.get(0)[3] + "";
				// String group1 = list2.get(0)[4] + "";
				session1.createSQLQuery(sql3).setParameter(0, DateTools.getCurrentDateTime()).setParameter(1, diefu1).setParameter(2, code).executeUpdate();
			}
			session1.getTransaction().commit();
			session1.clear();
			session1.close();
		}

	}

	@Override
	public JSONArray getLonghuitou(JSONObject json) {
		// TODO Auto-generated method stub

		String sql = "SELECT t1.* FROM ltmodel t1 INNER JOIN ( SELECT code1, MAX( group1 ) AS max_id FROM ltmodel GROUP BY code1 ) t2 ON t1.code1 = t2.code1 AND t1.group1 = t2.max_id ORDER BY t1.diefu DESC ";
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<Object[]> list = session1.createSQLQuery(sql).list();
		List<LTModel> list2 = new ArrayList<LTModel>();
		JSONArray jsonall = new JSONArray();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object[] objects = (Object[]) iterator.next();
			LTModel lt = new LTModel();
			lt.setTable_id(objects[0] + "");
			lt.setCreateTime(objects[1] + "");
			lt.setCode1(objects[2] + "");
			lt.setGroup1(objects[3] + "");
			lt.setName1(objects[4] + "");
			lt.setZtContent(objects[5] + "");
			lt.setDuolt(objects[6] + "");
			lt.setDiqv(objects[7] + "");
			lt.setDate(objects[8] + "");
			lt.setDiefu(objects[9] + "");
			list2.add(lt);
		}

		return jsonall.fromObject(list2);
	}

	@Override
	public List<StockCls> getZhuijinlaCls1(JSONArray jsonall) {
		// TODO Auto-generated method stub
		List<String> list2 = new ArrayList<String>();

		for (int i = 0; i < jsonall.size(); i++) {
			list2.add(jsonall.getJSONObject(i).getString("code").replace("sz", "").replace("sh", ""));
		}

		Session session1 = ContextUtil.getSessionFactory1().openSession();
//		String sql = "SELECT MAX(dqj) AS max_value FROM ( SELECT dqj FROM stockqq WHERE CODE = ?0 ORDER BY date DESC LIMIT 10 ) subquery";
//		for (int i = 0; i < jsonall.size(); i++) {
//			String code = jsonall.getJSONObject(i).getString("code").replace("sz", "").replace("sh", "");
//			String dqj = jsonall.getJSONObject(i).getString("jiage");
//			String temp = session1.createSQLQuery(sql).setParameter(0, code).uniqueResult().toString();
//			if (Float.parseFloat(dqj) < Float.parseFloat(temp)) {
//
//			} else {
//				System.out.println("dqj" + dqj + ":  历史：" + temp + "未下跌" + (1 - Float.parseFloat(tt)));
//			}
//			list2.add(code);
//		}
//		if (list2.size() == 0) {
//			return null;
//		}
		// TODO Auto-generated method stub
		String sql31 = "SELECT code,name, SUBSTRING_INDEX(gn, ',', -1) AS last_part,zt_content FROM stock_cls t where t.code in (?0);";
		List<Object[]> list = session1.createSQLQuery(sql31).setParameterList(0, list2).list();

		List<StockCls> listcls = new ArrayList<StockCls>();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object[] objects = (Object[]) iterator.next();
			StockCls sc = new StockCls();
			sc.setCode(objects[0] + "");
			sc.setName(objects[1] + "");
			sc.setGn(objects[2] + "");
			sc.setZtContent(objects[3] + "");
			listcls.add(sc);
		}

		return listcls;
	}

	public static List<String> listshouban = new ArrayList<String>();

	public static String listshouban1 = "";

	public static List<String> shoubanlist = new ArrayList<String>();

	@Override
	public JSONArray getTopShouban(JSONObject json) {

		SB.listall = new ArrayList<Stock1>();
		String text1 = json.getString("text1");
		if (text1.equals(listshouban1)) {

		} else {
			listshouban1 = text1;
			String[] str = text1.split(",");
			listshouban = Arrays.asList(str);
		}
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		shoubanlist = new ArrayList<String>();
		for (int i = 0; i < listshouban.size(); i++) {
			String sql = "select code from stock_cls t where t.shizhi <250  and t.zt_content like '%" + listshouban.get(i) + "%'";

			List<String> lista = session1.createSQLQuery(sql).list();
			shoubanlist.addAll(lista);
		}
		for (int i = 0; i < shoubanlist.size(); i++) {
			String code = shoubanlist.get(i);
			if (code.indexOf("6") == 0) {

				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			shoubanlist.set(i, code);
		}

		System.out.println("符合趋势有：" + shoubanlist.size() + JSONArray.fromObject(shoubanlist).toString());

		// TODO Auto-generated method stub

		System.out.println("调用启动首版数据");

		SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
		Date now = new Date();
		String formattedDate = sdf.format(now);

		for (int i = 0; i < shoubanlist.size(); i++) {
			List<TimeZDF> zdfList1 = new ArrayList<TimeZDF>();
			TimeZDF tz = new TimeZDF();
			tz.setTime(0L);
			tz.setZhangdiefu("0");
			Stock1 Stock1 = new Stock1();
			Stock1.setName(shoubanlist.get(i));
			Stock1.setZdfList(zdfList1);
			SB.listall.add(Stock1);
		}

		for (int i = 0; i < SB.listsu.size(); i++) {

			SB.listsu.get(i).stop();
		}

		StockDataUpdater updater = new StockDataUpdater();
		Thread updateThread = new Thread(updater);
		SB.listsu.add(updateThread);
		updateThread.start();
		session1.close();
		while (true) {
			try {
				Thread.sleep(10000);
				for (int i = 0; i < SB.listall.size(); i++) {

					if (i == 0) {
						// System.out.println(SB.listall.get(i).getZdfList().size());
						// System.out.println(JSONArray.fromObject(SB.listall.get(i).getZdfList()).toString());
					}
					DecimalFormat df = new DecimalFormat("0.00");
					// String result = df.format(num);
					int temp = SB.listall.get(i).getZdfList().size();
					String cz = SB.listall.get(i).getZdfList().get(temp - 1).getZhangdiefu();

					if (SB.listall.get(i).getZdfList().size() >= 12) {
						String cz1 = SB.listall.get(i).getZdfList().get(temp - 12).getZhangdiefu();
						// System.out.println(Float.parseFloat(cz1) - Float.parseFloat(cz));
						// if(Float.parseFloat(cz) - Float.parseFloat(cz1) >=2) {
						// SB.listsbresult1.add(SB.listall.get(i).getName());
						SB.map1.put(SB.listall.get(i).getName(), df.format(Float.parseFloat(cz) - Float.parseFloat(cz1)) + "");
						// }
					}
					if (SB.listall.get(i).getZdfList().size() >= 35) {
						String cz3 = SB.listall.get(i).getZdfList().get(temp - 35).getZhangdiefu();
						// System.out.println(Float.parseFloat(cz3) - Float.parseFloat(cz));
						// if(Float.parseFloat(cz) - Float.parseFloat(cz3) >=2) {
						// SB.listsbresult3.add(SB.listall.get(i).getName());
						SB.map3.put(SB.listall.get(i).getName(), df.format(Float.parseFloat(cz) - Float.parseFloat(cz3)) + "");
						// }
					}
					if (SB.listall.get(i).getZdfList().size() >= 59) {
						String cz5 = SB.listall.get(i).getZdfList().get(temp - 59).getZhangdiefu();
						// System.out.println(Float.parseFloat(cz5) - Float.parseFloat(cz));
						// if(Float.parseFloat(cz) - Float.parseFloat(cz5) >=2) {
						// SB.listsbresult5.add(SB.listall.get(i).getName());
						SB.map5.put(SB.listall.get(i).getName(), df.format(Float.parseFloat(cz) - Float.parseFloat(cz5)) + "");
						// }
					}

				}
				System.out.println("1分钟内涨了5个点的：" + JSONArray.fromObject(SB.map1).toString());
				System.out.println("3分钟内涨了5个点的：" + JSONArray.fromObject(SB.map3).toString());
				System.out.println("5分钟内涨了5个点的：" + JSONArray.fromObject(SB.map5).toString());

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	@Transactional
	// @Scheduled(cron = "0 40 23 * * ?")
	@Override
	public void topShouban() {

		SB1.listall.clear();
		String[] gnlist = { "机器人", "AI", "DeepSeek", "零售", "算力", "固态电池" };
		System.out.println("开始调用计算首版code" + JSONArray.fromObject(gnlist).toString());
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String gnstring = "";
		for (int i = 0; i < gnlist.length; i++) {
			if (i == 0) {
				gnstring += " t.zt_content like '%" + gnlist[i] + "%'  ";
			} else {
				gnstring += " or t.zt_content like '%" + gnlist[i] + "%'  ";
			}
		}
		// String sql="select code1 from ltmodel t where 1=1 and (" + gnstring + ")";
		String sql = "select code from stock_cls t where t.shizhi < 250 and t.shizhi > 50  and (" + gnstring + ")";
		List<String> list = session1.createSQLQuery(sql).list();
		String sql1 = "select zhangdiefu from stockqq t where  t.code = ?0  and t.date > ?1 order by t.date desc";
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -15);
		Date date = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String result = sdf.format(date);
		System.out.println("15天前为：" + result);
		calendar.add(Calendar.DATE, -60);
		Date date1 = calendar.getTime();
		String result1 = sdf.format(date1);
		System.out.println("60天前为：" + result1);
		String sql2 = "select count(*) from stockqq t where t.code =?0 and zhangdiefu >=?1 and t.date >?2 ";

		for (int i = 0; i < list.size(); i++) {

			String code = list.get(i);
			List<String> list1 = session1.createSQLQuery(sql1).setParameter(0, code).setParameter(1, result).list();
			List<Float> floatList = list1.stream().map(Float::valueOf).collect(Collectors.toList());
			Optional<Float> max = floatList.stream().max(Float::compareTo);
			Optional<Float> min = floatList.stream().min(Float::compareTo);
			if (max.isPresent()) {
				// System.out.println(code + "最大值: " + max.get());
				if (max.get() >= 6.5f) {
					// System.out.println(code + "最近10天有数据大于6.5退出");
					continue;
				}
			}
			if (min.isPresent()) {
				// System.out.println(code + "最小值: " + min.get());
				if (max.get() <= -6) {
					// System.out.println(code + "最近10天有数据小于-6退出");
					continue;
				}
			}
			if (floatList.get(0) >= 4 && floatList.get(1) >= 4) {
				// System.out.println(code + "最近两天连续大于4个点退出");
				continue;
			}
			String count = session1.createSQLQuery(sql2).setParameter(0, code).setParameter(1, 5).setParameter(2, result1).uniqueResult().toString();

			if (Integer.parseInt(count) <= 1) {
				// System.out.println(code + "最近没有大于5的数据少于2不符合要求");
				continue;
			}

			Stock1 stock1 = new Stock1();
			if (code.indexOf("6") == 0) {
				stock1.setName("sh" + code);
			} else {
				stock1.setName("sz" + code);
			}

			SB1.listall.add(stock1);

			System.out.println(code + "增加符合首版运算");
			System.out.println("共" + list.size() + "只，计算到" + i + "只，共有符合首版运算：" + SB1.listall.size());

		}

		String sql3 = "select min(t.dqj),t.code from stockqq t  GROUP BY  t.code ";

		List<Object[]> list3 = session1.createSQLQuery(sql3).list();

		List<String> allcode = new ArrayList<String>();

		for (int i = SB1.listall.size() - 1; i >= 0; i--) {
			allcode.add(SB1.listall.get(i).getName());
		}

		JSONArray jsonlist = StockContrl.getCcc(String.join(",", allcode), 1f);
		System.out.println("拉取当前getCCC数据:" + jsonlist.size());

		for (int i = jsonlist.size() - 1; i >= 0; i--) {
			JSONObject json = jsonlist.getJSONObject(i);
			Float dqj = Float.parseFloat(json.get("jiage") + "");
			String code = json.getString("code");
			for (int j = list3.size() - 1; j >= 0; j--) {
				String CODE = list3.get(j)[1] + "";
				if (code.indexOf(CODE) >= 0) {
					Float dqjmysql = Float.parseFloat(list3.get(j)[0] + "");
					if (dqj <= dqjmysql * 1.3) {

					} else {
						jsonlist.remove(i);
					}
					break;
				}
			}
		}
		System.out.println("符合没有涨超40%的有:" + jsonlist.size());
		session1.beginTransaction();
		session1.createSQLQuery("delete from sbstock where 1=1").executeUpdate();

		for (int i = SB1.listall.size() - 1; i >= 0; i--) {
			String code = SB1.listall.get(i).getName();

			boolean b = false;
			for (int j = jsonlist.size() - 1; j >= 0; j--) {
				String code1 = jsonlist.getJSONObject(j).getString("code");
				if (code.equals(code1)) {
					b = true;
					break;
				}
			}
			if (b == false) {
				System.out.println("不符合：相较最小值已经涨超40%");
				SB1.listall.remove(i);
			}
		}
		System.out.println("最终符合条件:" + SB1.listall.size());
		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
		String timeStr2 = now.format(formatter1);
		for (int i = 0; i < SB1.listall.size(); i++) {
			SBStock sbs = new SBStock();
			sbs.setStockcode(SB1.listall.get(i).getName());
			sbs.setCreateTime(timeStr2);
			session1.save(sbs);
		}
		session1.getTransaction().commit();
		session1.clear();
		session1.close();
	}

	@Transactional
	@Scheduled(cron = "0 40 23 * * ?")
	@Override
	public void topShoubanLt() {

		SB1.listall.clear();
		String[] gnlist = { "机器人", "AI", "DeepSeek", "零售", "算力", "固态电池" };
		System.out.println("开始调用计算首版code" + JSONArray.fromObject(gnlist).toString());
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String gnstring = "";
		for (int i = 0; i < gnlist.length; i++) {
			if (i == 0) {
				gnstring += " t.zt_content like '%" + gnlist[i] + "%'  ";
			} else {
				gnstring += " or t.zt_content like '%" + gnlist[i] + "%'  ";
			}
		}
		String sql = "select code1 from ltmodel t where 1=1 and (" + gnstring + ")";
		// String sql = "select code from stock_cls t where t.shizhi < 250 and t.shizhi > 50 and (" + gnstring + ")";
		List<String> list = session1.createSQLQuery(sql).list();

		for (int i = 0; i < list.size(); i++) {

			String code = list.get(i);

			Stock1 stock1 = new Stock1();
			if (code.indexOf("6") == 0) {
				stock1.setName("sh" + code);
			} else {
				stock1.setName("sz" + code);
			}

			SB1.listall.add(stock1);

			System.out.println(code + "增加符合首版运算");
			System.out.println("共" + list.size() + "只，计算到" + i + "只，共有符合首版运算：" + SB1.listall.size());

		}

		String sql3 = "select min(t.dqj),t.code from stockqq t  GROUP BY  t.code ";

		List<Object[]> list3 = session1.createSQLQuery(sql3).list();

		List<String> allcode = new ArrayList<String>();

		for (int i = SB1.listall.size() - 1; i >= 0; i--) {
			allcode.add(SB1.listall.get(i).getName());
		}

		JSONArray jsonlist = StockContrl.getCcc(String.join(",", allcode), 1f);
		session1.beginTransaction();
		session1.createSQLQuery("delete from sbstock where 1=1").executeUpdate();
		System.out.println("最终符合条件:" + SB1.listall.size());
		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
		String timeStr2 = now.format(formatter1);
		for (int i = 0; i < SB1.listall.size(); i++) {
			SBStock sbs = new SBStock();
			sbs.setStockcode(SB1.listall.get(i).getName());
			sbs.setCreateTime(timeStr2);
			session1.save(sbs);
		}
		session1.getTransaction().commit();
		session1.clear();
		session1.close();
	}

	public static boolean isTimeDiffGreaterThanFiveMinutes(String time1, String time2) {
		int seconds1 = convertToSeconds(time1);
		int seconds2 = convertToSeconds(time2);
		int diff = Math.abs(seconds1 - seconds2);
		return diff > 300;
	}

	public static int convertToSeconds(String time) {
		int hours = Integer.parseInt(time.substring(0, 2));
		int minutes = Integer.parseInt(time.substring(2, 4));
		int seconds = Integer.parseInt(time.substring(4));
		return hours * 3600 + minutes * 60 + seconds;
	}

	@Override
	public void save(Stocksb stocksb, int mapN) {

		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
		String timeStr = now.format(formatter);
		for (int i = 0; i < SB1.map135.size(); i++) {
			if (SB1.map135.get(i).getCode1().equals(stocksb.getCode()) && SB1.map135.get(i).getMapN().equals(mapN + "")) {
				String t1 = SB1.map135.get(i).getCreateTime();
				boolean b = isTimeDiffGreaterThanFiveMinutes(t1, timeStr);
				if (b == false) {
					return;
				}
			}
		}

		// TODO Auto-generated method stub

		DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
		String timeStr2 = now.format(formatter1);
		SBStock135 sb135 = new SBStock135();
		sb135.setCode1(stocksb.getCode());
		sb135.setMapN(mapN + "");
		sb135.setCreateTime(timeStr);
		sb135.setDay(timeStr2);
		sb135.setZdf(stocksb.getZdf() + "");
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		session1.beginTransaction();
		session1.save(sb135);
		session1.getTransaction().commit();
		session1.close();
		SB1.map135.add(sb135);

	}

	public static JSONArray sbStockjson = new JSONArray();

	@Transactional
	@Scheduled(cron = "0 50 17 * * ?")
	@Override
	public void redianGuanzhu() {

		System.out.println("计算当前所有sbstock的股票的排序问题");
		sbStockjson.clear();
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql = "select REPLACE(REPLACE(stockcode,'sh',''),'sz','') from sbstock t ";
		List<String> list = session1.createSQLQuery(sql).list();
		String sql3 = "select min(t.dqj),max(t.dqj),code from stockqq t where t.code in (?0)  GROUP BY t.code";
		List<Object[]> list3min = session1.createSQLQuery(sql3).setParameterList(0, list).getResultList();
		String sql4 = "select t.dqj,code from stockqq t where t.code in (?0) and t.date =(select max(t1.date) from stockqq t1)";
		List<Object[]> list4cc = session1.createSQLQuery(sql4).setParameterList(0, list).getResultList();
		String sql1 = "";

		String sql5 = "select cjje from stockqq t where t.code =?0 limit 0,3 ";

		for (int i = 0; i < list3min.size(); i++) {

			Float mindjq = Float.parseFloat(list3min.get(i)[0] + "");
			Float maxdjq = Float.parseFloat(list3min.get(i)[1] + "");
			String code = list3min.get(i)[2] + "";
			for (int j = 0; j < list4cc.size(); j++) {
				Float dqj = Float.parseFloat(list4cc.get(j)[0] + "");
				String code1 = list4cc.get(j)[1] + "";
				if (code.equals(code1)) {

					List<String> list5 = session1.createSQLQuery(sql5).setParameter(0, code).list();
					List<Float> floatList = list5.stream().map(Float::valueOf).collect(Collectors.toList());

					float bodonglv = calculateAverageVolatility(floatList);
					JSONObject josn = new JSONObject();

					if (code.indexOf("6") == 0) {
						code = "sh" + code;
						josn.put("code", code);
					} else {
						code = "sz" + code;
						josn.put("code", code);
					}

					josn.put("min", mindjq);
					josn.put("max", maxdjq);
					josn.put("dqj", dqj);
					josn.put("julizuixiao", (dqj - mindjq) / mindjq);
					josn.put("julizuida", (maxdjq - dqj) / maxdjq);
					josn.put("bodonglv", bodonglv);
					String gn = SBService.getZTnote(code);
					josn.put("gn", gn);
					sbStockjson.add(josn);
					continue;
				}
			}

		}
		System.out.println(sbStockjson.toString());
	}

	public static float calculateAverageVolatility(List<Float> list) {
		if (list == null || list.size() < 2) {
			return 0.0f;
		}

		float sumVolatility = 0.0f;
		int count = list.size() - 1;

		for (int i = 1; i < list.size(); i++) {
			float prev = list.get(i - 1);
			float cur = list.get(i);
			sumVolatility += Math.abs((cur - prev) / prev);
		}

		return sumVolatility / count;
	}

	// @Scheduled(cron = "0/10 * * * * ?")
	@Override
	public void addSbstock135() {
		if (!StockDataUpdater2.isTimeInRange()) {
			System.out.println("每10秒监控一次执行 --当前时间不在9:15到15:00之间");
			return;
		}
		System.out.println("每10秒监控一次执行");
		for (int i = 0; i < SB1.map5.size(); i++) {
			if (SB1.map5.get(i).getZdf() >= 4) {
				this.save(SB1.map5.get(i), 5);
			}

		}
		for (int i = 0; i < SB1.map3.size(); i++) {
			if (SB1.map3.get(i).getZdf() >= 2.3) {
				this.save(SB1.map3.get(i), 3);
			}

		}
		for (int i = 0; i < SB1.map1.size(); i++) {
			if (SB1.map1.get(i).getZdf() >= 1.5) {
				this.save(SB1.map1.get(i), 1);
			}

		}

	}

	public static List<String> list100 = new ArrayList<String>();

	public static List<String> list1001 = new ArrayList<String>();

	@Transactional
	@Scheduled(cron = "0 35 16 * * ?")
	@Override
	public void topShoubanLt100() {

		System.out.println("开始计算100亿以上，11个工作日没有上涨超过7个点的票");
		list100.clear();
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_YEAR, -11);
		Date date = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String result = sdf.format(date);
		String sql = "select DISTINCT(code) from stockqq t where t.shizhi >=100 and t.shizhi <=300 ";

		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<String> str = session1.createSQLQuery(sql).list();
		String sql1 = "";
		String sql2 = "select  count(*)  from stockqq t where t.date > ?0  and t.code =?1  and t.zhangdiefu  >= 7";

		String sql3 = " select sum(zhangdiefu) from (select t.zhangdiefu  from  stockqq t where t.code =?0 order by t.date desc  limit 0,3) as t2";
		for (int i = 0; i < str.size(); i++) {
			String code = str.get(i);

			int f1 = Integer.parseInt(session1.createSQLQuery(sql2).setParameter(0, result).setParameter(1, code).uniqueResult().toString());

			Float f2 = Float.parseFloat(session1.createSQLQuery(sql3).setParameter(0, code).uniqueResult().toString());

			System.out.println("三日涨跌总和为："+f2);
			
			if (f2 <= -10f) {
				System.out.println("三日内跌超过17%，符合要求");
				list100.add(code);
				list1001.add(code);
				continue;
			}
			if (f1 >= 1) {
				System.out.println("不符合要求有>7" + code + "==" + i);
				continue;
			}
			System.out.println("符合要求没有有>7" + code + "==" + i);
			list100.add(code);
		}
		System.out.println("共有100亿的没有上涨超过7个点的票有==" + list100.size());
	}

	@Transactional
	// @Scheduled(cron = "0 20 09 * * ?")
	@Override
	public void startSbstock135Thread() {
		System.out.println("启动线程开始监控分分涨数据");
		for (int i = 0; i < SB1.listsu.size(); i++) {
			SB1.listsu.get(i).stop();
		}
		SB1.map1.clear();
		SB1.map3.clear();
		SB1.map5.clear();
		StockDataUpdater2 updater = new StockDataUpdater2();
		Thread updateThread = new Thread(updater);
		SB1.listsu.add(updateThread);
		updateThread.start();
	}

	@Override
	public JSONArray getTop100(JSONObject json) {
		// TODO Auto-generated method stub
		// String sql = "select DISTINCT(code) from stockqq t where t.shizhi >=100 and t.shizhi <=300 ";

		Session session1 = ContextUtil.getSessionFactory1().openSession();
		// List<String> str = session1.createSQLQuery(sql).list();
		String sql1 = "";

		String[] gnlist = json.getString("gn").split(",");

		String gnstring = "";
		for (int i = 0; i < gnlist.length; i++) {
			if (i == 0) {
				gnstring += " t.gn like '%" + gnlist[i] + "%'  ";
			} else {
				gnstring += " or t.gn like '%" + gnlist[i] + "%'  ";
			}
		}

		sql1 = "select code,gn,name,shizhi,zt_content from stock_cls t where t.code in (?0) and (" + gnstring + ")";

		List<Object[]> list = session1.createSQLQuery(sql1).setParameterList(0, list100).list();

		JSONArray arr = new JSONArray();

		for (int i = 0; i < list.size(); i++) {
			JSONObject json1 = new JSONObject();
			String code = list.get(i)[0] + "";
			if (code.indexOf("6") == 0) {
				json1.put("code", "sh" + code);
			} else {
				json1.put("code", "sz" + code);
			}
			json1.put("gn", list.get(i)[1] + "");
			json1.put("name", list.get(i)[2] + "");
			json1.put("shizhi", list.get(i)[3] + "");
			json1.put("zt_content", list.get(i)[4] + "");
			arr.add(json1);
		}

		return arr;
	}

	@Override
	public JSONArray getTop1001(JSONObject json) {
		// TODO Auto-generated method stub
		// String sql = "select DISTINCT(code) from stockqq t where t.shizhi >=100 and t.shizhi <=300 ";

		Session session1 = ContextUtil.getSessionFactory1().openSession();
		// List<String> str = session1.createSQLQuery(sql).list();
		String sql1 = "";

		String[] gnlist = json.getString("gn").split(",");

		String gnstring = "";
		for (int i = 0; i < gnlist.length; i++) {
			if (i == 0) {
				gnstring += " t.gn like '%" + gnlist[i] + "%'  ";
			} else {
				gnstring += " or t.gn like '%" + gnlist[i] + "%'  ";
			}
		}

		sql1 = "select code,gn,name,shizhi,zt_content from stock_cls t where t.code in (?0) and (" + gnstring + ")";

		List<Object[]> list = session1.createSQLQuery(sql1).setParameterList(0, list1001).list();

		JSONArray arr = new JSONArray();

		for (int i = 0; i < list.size(); i++) {
			JSONObject json1 = new JSONObject();
			String code = list.get(i)[0] + "";
			if (code.indexOf("6") == 0) {
				json1.put("code", "sh" + code);
			} else {
				json1.put("code", "sz" + code);
			}
			json1.put("gn", list.get(i)[1] + "");
			json1.put("name", list.get(i)[2] + "");
			json1.put("shizhi", list.get(i)[3] + "");
			json1.put("zt_content", list.get(i)[4] + "");
			arr.add(json1);
		}

		return arr;
	}

}
